<?php
namespace app\admin\controller;

use think\Db;

class Role extends Base
{
	public function role()
	{
        if ($this->request->isPost() && $this->request->isAjax()) {
            // 查询
            $map = [];

            // 分页
            $page = $this->request->param('page/d', 0);
            $limit = $this->request->param('limit/d', 0);
            $count = Db::table('role')->where($map)->count();
            
            $data = Db::table('role')->where($map)->limit($limit * ($page - 1), $limit)->order('id desc')->select();

            // 返回数据
            $res = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $data,
            ];

            return json($res);
        }

        $this->assign('menu', config('menu.'));

		return $this->fetch();
	}

    public function roleSave()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/d', 0);
            $data = [
                'name'  =>  $this->request->param('name/s', ''),
                'conts' =>  implode(',', $this->request->param('conts/a', [])),
            ];

            // 校验重复
            $map = [];
            $map[] = ['id', '<>', $id];
            $map[] = ['name', '=', $data['name']];
            if (Db::table('role')->where($map)->count()) {
                $this->result('', 1, '角色名称重复');
            }

            // 添加编辑状态检测
            if ($id) {
                if (!Db::table('role')->where('id', $id)->update($data)) {
                    $this->result('', 1, '编辑角色失败');
                }
            } else {
                if (!Db::table('role')->insert($data)) {
                    $this->result('', 1, '添加角色失败');
                }
            }

            $this->result('', 0, '保存成功');
        }
    }

    public function roleDel()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/d', 0);

            if (Db::table('user')->where('role_id', $id)->count()) {
                $this->result('', 1, '请先删除或调整此角色下的用户');
            }

            if (!Db::table('role')->delete($id)) {
                $this->result('', 1, '删除失败');
            }

            $this->result('', 0, '删除成功');
        }
    }
}
